import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:kxy_flutter_app/model/course_category.dart';
import 'package:kxy_flutter_app/r.dart';
import 'package:kxy_flutter_app/services/course_service.dart';
import 'package:kxy_flutter_app/view/course/course_cate_view.dart';
import 'package:kxy_flutter_app/view/course/course_list_View.dart';
import 'package:kxy_flutter_app/view/course/course_list_widget.dart';
import 'package:kxy_flutter_app/view/root/view_model/app_info_model.dart';
import 'package:provider/provider.dart';

class CourseView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return CourseViewState();
  }
}

class CourseViewState extends State<CourseView> with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  CourseService courseService = new CourseService();
  List<CourseCategory> cateList = new List<CourseCategory>();
  Future loadFuture;
  TabController tabController;
  TextEditingController searchTextCtrl = new TextEditingController();

  @override
  void initState() {
    tabController = new TabController(length: 0, vsync: this);
    loadFuture = courseService.getCateList().then((value) {
      setState(() {
        cateList = value;
        tabController = new TabController(length: cateList.length, vsync: this);
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        leading: Consumer<AppInfoModel>(
          builder: (cxt, vm, child) {
            return Container(
              margin: EdgeInsets.fromLTRB(10, 10, 10, 10),
              child: vm.logoUrl.isEmpty
                  ? Image.asset(R.assetsCommonLogo)
                  : CachedNetworkImage(
                      imageUrl: vm.logoUrl,
                      fit: BoxFit.fitHeight,
                    ),
            );
          },
        ),
        title: searchField(),
        centerTitle: true,
        actions: [
          IconButton(
            icon: Image.asset(
              R.assetsCommonCourseCate,
              height: 20,
            ),
            onPressed: () {
              Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (cxt) => CourseCateView(cateList: cateList),
                ),
              );
            },
          ),
        ],
        bottom: tabbar(),
      ),
      body: FutureBuilder(
        future: loadFuture,
        initialData: [],
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return tabView();
          }
          return Container();
        },
      ),
    );
  }

  Widget tabbar() {
    return PreferredSize(
      preferredSize: Size(MediaQuery.of(context).size.width, 42),
      child: Container(
        alignment: Alignment.centerLeft,
        child: TabBar(
          tabs: createTabs(),
          isScrollable: true,
          controller: tabController,
          labelPadding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
          unselectedLabelColor: Colors.black54,
          unselectedLabelStyle: TextStyle(fontWeight: FontWeight.normal, fontSize: 16),
          labelColor: Theme.of(context).primaryColor,
          labelStyle: TextStyle(fontWeight: FontWeight.normal, fontSize: 16),
          indicatorSize: TabBarIndicatorSize.label,
          indicatorColor: Theme.of(context).primaryColor,
          indicatorWeight: 3,
          indicatorPadding: EdgeInsets.fromLTRB(10, 0, 10, 0),
        ),
      ),
    );
  }

  Widget tabView() {
    return TabBarView(
      children: cateList.map((item) {
        return CourseListWidget(cateId: item.id);
      }).toList(),
      controller: tabController,
    );
  }

  List<Widget> createTabs() {
    return cateList.map((cate) {
      return Text(cate.name);
    }).toList();
  }

  Widget searchField() {
    return ConstrainedBox(
      constraints: BoxConstraints(
        maxHeight: 32,
        maxWidth: 300,
      ),
      child: TextField(
        onEditingComplete: () {
          return Navigator.of(context).push(
            MaterialPageRoute(
              builder: (cxt) => CourseListView(searchText: searchTextCtrl.text),
            ),
          );
        },
        controller: searchTextCtrl,
        decoration: InputDecoration(
          filled: true,
          hintText: '请输入搜索内容',
          contentPadding: const EdgeInsets.symmetric(vertical: 0),
          prefixIcon: Icon(
            Icons.search,
            color: Colors.black54,
            size: 16,
          ),
          fillColor: Color.fromRGBO(240, 240, 240, 1),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(5),
            borderSide: BorderSide.none,
          ),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => false;
}
